import BaseVue from '@/lib/base/BaseVue';
import Component from 'vue-class-component';
import S, { SwiperOptions } from 'swiper';
import { Prop } from 'vue-property-decorator';

@Component
export default class extends BaseVue {
    private mSwiper!: S;
    @Prop()
    private config!: SwiperOptions;

    public render() {
        return (
            <div class="swiper-container" >
                <div class="swiper-wrapper">
                    {this.$slots.default}
                </div>
                {this.$slots.container}
            </div>
        )
    }

    public mounted() {
        this.initSwiper();
    }

    public updated() {
        if (this.mSwiper) {
            this.autoReLoop();
            this.mSwiper.update();
            if (this.mSwiper.pagination) {
                this.mSwiper.pagination.update();
                this.mSwiper.pagination.render();
                this.mSwiper.pagination.update();
            }

        } else {
            this.initSwiper();
        }

    }

    public beforeDestroy() {
        if (this.mSwiper) {
            this.$nextTick(() => {
                this.mSwiper.destroy();
            });
        }
    }

    public initSwiper() {
        if (!this.$slots.default || this.$slots.default.length === 0) {
            return;
        }
        const container = this.$el as HTMLElement;
        import(/* webpackChunkName: "Swiper" */'swiper/swiper.less').then(() => {
            import(/* webpackChunkName: "Swiper" */'swiper/bundle').then((module) => {
                this.mSwiper = new module.default(container, {
                    ... this.config,
                });
                this.$emit('load');
            });
        });
    }

    public getSwiper() {
        return this.mSwiper;
    }

    /**
     * 重置加载
     */
    private autoReLoop() {
        if (this.mSwiper && this.config.loop) {
            const swiper = this.mSwiper as any;
            swiper.loopDestroy();
            swiper.loopCreate();
            swiper.loopFix();
        }
    }
}
